package html;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.xml.parsers.ParserConfigurationException;

import lib.ConnectionWeb;
import lib.LevenshteinDistance;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.DoctypeToken;
import org.htmlcleaner.DomSerializer;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import pojo.Charconvert;

import dao.CharConvertDAO;
import dao.LogDAO;

public class HtmlAdapter {
	private DefaultMutableTreeNode root;
	private static Document document=null;
	private static List<Charconvert> l;
	private String url;
    private ConnectionWeb web;
    
    
	public HtmlAdapter(String htmlTring)
	{
		Document doc = Jsoup.parse(htmlTring);
		
		document=doc;
		Element rootDom = doc.children().first();
		root= new DefaultMutableTreeNode(convert(rootDom));
		//rootNode=new HtmlTreeNode(convert(rootDom));
		Elements le= rootDom.children();
		for(Element e : le)
		{
			addNode(root, e);
		}
        CharConvertDAO dao= new CharConvertDAO();
        l=dao.getList();
        web=new ConnectionWeb();
	}
	
	public HtmlAdapter() {
		// TODO Auto-generated constructor stub
        CharConvertDAO dao= new CharConvertDAO();
        l=dao.getList();
        web=new ConnectionWeb();
	}
	
	public void setUrl(String s)
	{
		if(s.indexOf("www")==-1) s="http://www."+s.substring(7,s.length());
		url=s;
	
	
		String html=web.connect(url);
		if(html==null||html.equals(""))
		{
			try {
			document= Jsoup.connect(url)
					  .data("query", "Java")
					  .userAgent("Mozilla")
					  .cookie("auth", "token")
					  .timeout(6000)
					  .post();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

		}
		else
		{
			document=Jsoup.parse(html);
		}
		Element rootDom = document.children().first();
		root= new DefaultMutableTreeNode(convert(rootDom));
		Elements le= rootDom.children();
		for(Element e : le)
		{
			addNode(root, e);
		}
		
	}
	public void setHtmlString(String st)
	{
		Document doc = Jsoup.parse(st);
		document=doc;
		System.out.println("asd");
	}
	
	public DefaultMutableTreeNode  getRoot()
	{
		return root;
	}
	
	
	public String convert(Element e)
	{
		String t="";
		t="<"+e.nodeName();
		Attributes  la=e.attributes();
		for(Attribute a: la)
		{
			t+=" "+a.getKey()+"=\""+a.getValue()+"\"";
		}
		t+=">"+e.ownText();
		return t;
	}
	
	
	public String getXpath(String html)
	{
		String xpath="";
		String css="html body table#out tbody tr td table#middle tbody tr td table#left tbody tr td table#mnLeft tbody tr td div#menu ul li";
		Elements le=document.getAllElements();
		Elements lee=document.select(css);
		Element te = null;
		
	
		for(Element e:lee)
		{
			String s=e.outerHtml();
			s=convertToUTF8(s);
			if(s.equals(html))
			{
				te=e;
			};
		}
		System.out.print(te.text());
		return xpath;
	}
	
	
    public static String convertToUTF8(String s) {
        String out = null;

        
        for(int i=0;i<l.size();i++)
        {
        	String t=l.get(i).getIsoCode();
        	s=s.replace(t, l.get(i).getCharactor());
        }
        return s;
    }
    
   
    public MyString getPath(String html)
    {
    	String temp_html=html;
    	int htmllen=html.length();
    	int n2=html.indexOf("<");
    	int m=html.indexOf(" ",n2);
    	int m2=html.indexOf(">",n2);
    	String st="";
    	if(m>m2)
    	{
    		st=html.substring(n2+1,m2);
    	}
    	else
    	{
    		st=html.substring(n2+1,m);
    	}
		html=html.toLowerCase();
		html=removeBorder3(html);

		Element te = null;
		Elements le=document.getElementsByTag(st);
	/*	for(Element e:le)
		{
			String s=e.outerHtml();
			System.out.println(s.length());
			if(Math.abs(s.length()-htmllen)>5000) continue;
			s=s.toLowerCase();
			s=removeBorder3(s);
			if(html.length()>10000&&s.length()>10000)
			{
				String thtml=html.substring(0,9000);
				s=s.substring(0,9000);
				if(s.equals(thtml))
				{
					te=e;
					continue;
				};
			}
			else
			{	
				if(s.equals(html))
				{
					te=e;
					continue;
				};
			}
			
			if(s.length()>1000&&html.length()>1000)
			{
				s=s.substring(0,1000);
				String as=html.substring(0,1000);
				if(s.equals(as))
				{
					te=e;
				}
			}
		}
				*/						
		if(te==null)
		{
			LogDAO.insert("Không tìm thấy node tương ứng "+st +" chay code tam 2");
			te=getE(temp_html);
			
		}	
		if(te==null)
		{
			LogDAO.insert("Không tìm thấy node tương ứng "+st +" chay code tam 2");
			te=getE2(temp_html);
			
		}	
		
		if(te==null)
		{
			LogDAO.insert("Không tìm thấy "+st +"sau khi chay 2 lan");
		}
		else
		{
			Elements lp=te.parents();
			int n=lp.size()+1;
			MyString tree=new MyString(n);
	
			tree.setPathAt(n-1,te.tagName());
			tree.setIndexAt(n-1, getIndex(te));
			int dem=n-2;
			
			for(Element t:lp)
			{
				tree.setPathAt(dem,t.tagName());
				tree.setIndexAt(dem, getIndex(t));
				dem--;
				
			}		
			
			return tree;
		
		}
		
		return null;
    
    }
    
    public int getIndex(Element t)
    {
    	int n=0;
    	Element t2=t.parent();
    	Elements l=t2.children();
    	for(int i=0;i< l.size();i++)
    	{
    		Element t3=l.get(i);
    		if(t.toString().equals(t3.toString()))
    		{
    			n=i;
    			break;
    		}
    	}
    	int dem=0;
    	String name=t.tagName();
    	for(int i= 0;i<n;i++)
    	{
    		String st=l.get(i).tagName();
    		if(st.equals(name))
    			dem++;
    	}
    	
    	
    	return dem;
    }
    public void getParent()
    {
    	
    }
    
    
    public void addNode(DefaultMutableTreeNode pa,Element e)
	{
		Elements le=e.children();
		if(le.size()==0)
		{
			String t= convert(e);
			DefaultMutableTreeNode kid= new DefaultMutableTreeNode(t);
			pa.add(kid);
		}
		else
		{	
			String t= convert(e);
			DefaultMutableTreeNode kid= new DefaultMutableTreeNode(t);
			pa.add(kid);
			for(Element el:le)
			{
				addNode(kid,el);
			}
		}
	}
    
    public String getname(String t)
    {
    	int n1=t.indexOf(">");
    	int n2=t.indexOf(" ");
    	String st="";
    	if(n2==-1||n2>n1)
    	{
    		st=t.substring(1,n1);
    	}
    	else
    	{
    		st=t.substring(1,n2);
    	}
    	return st;
    	
    }
    public TreePath getTreePath(JTree tree, MyString path2)
    {
    	
    	
    	//doan code hay
    /*	for(int i=1;i<path2.length;i++)
    	{
    		for(int j=0;j<node.getChildCount();j++)
    		{
    			if(f==false) j=dem+1;
    			TreeNode t2=node.getChildAt(j);
    			
    			if(t2.toString().equals(path2[i]))
    			{
    				dem=j;
    				tp=tp.pathByAddingChild(t2);
    				node=t2;
    				f=true;
    				break;
    			}
    			
    			if(j==node.getChildCount()-1&&i<path2.length-1)
    			{
    				f=false;
    				node=node.getParent();
    				tp=tp.getParentPath();
    				i--;
    			}
    			
    			
    		}
    		
    		
    	}*/
    	TreeNode node=(TreeNode) tree.getModel().getRoot();
    	TreePath tp=new TreePath(node);
    	TreeNode t=node;

    	boolean f=true;
    	int[] index=path2.getIndex();
    	String[] path=path2.getPath();
    	//String[] path=path2.getPath();
    	for(int i=1;i<index.length;i++)
    	{
    		int dem=0;
    		TreeNode t2=null;
    		for(int j=0;j<node.getChildCount();j++)
    		{
    			String st;
    			TreeNode tn=node.getChildAt(j);
    			st=getname(tn.toString());
    			if(path[i].equals(st))
    			{
    				if(dem==index[i])
    				{
    					t2=tn;
    					break;
    				}
    				else
    					dem++;
    			}
    		}
    		
    		if(t2!=null)
    		{
	    		tp=tp.pathByAddingChild(t2);
				node=t2;  
				
				if(i==index.length-1)
				{
					if(t2.isLeaf()==true)
					{
						tp=tp.getParentPath();
					}
				}
    		}
    		else
    		{
    			LogDAO.insert("loi tree path");
    		}
    	}
    	
    	return tp;
    }
    
    
    private void collapseAll(JTree tree, TreePath parent) {
	    TreeNode node = (TreeNode) parent.getLastPathComponent();
	    if (node.getChildCount() >= 0) {
	      for (Enumeration e = node.children(); e.hasMoreElements();) {
	        TreeNode n = (TreeNode) e.nextElement();
	        TreePath path = parent.pathByAddingChild(n);
	        collapseAll(tree, path);
	      }
	    }
	   // tree.expandPath(parent);
	     tree.collapsePath(parent);
	  }
    
    
    public  void collapseTree(JTree tree) {
    	TreePath path= new TreePath(tree.getModel().getRoot());
    	collapseAll(tree,path);
    }
    
    public String removeBorder(String s)
    {
    	s=s.toLowerCase();
    	int n2=0;
    	int dem=0;
    	while(s.indexOf("style=",n2)!=-1)
    	{
    		int n=s.indexOf("style=")-1;
    		int m=s.indexOf("\"",n+8);	
    		String t="";
    		if(n!=-1&&m!=-1)
    		t=s.substring(n,m+1);
    		s=s.replace(t,"");
    		
    	}
    	s=s.replaceAll("\n","");
		s=s.replaceAll("\r","");
		s=s.replaceAll(" ","");
		s=convertToUTF8(s);
		s=s.replaceAll("\"","");
		s=s.replaceAll("/","");
		s=s.replaceAll("=","");
		s=s.replaceAll("true","");
		s=s.replaceAll("no","");
		for(int i=0;i<10;i++)
		{
			s=s.replaceAll(Integer.toString(i),"");
		}
		
    	return s;
    }
    public String removeBorder2(String s)
    {
    	s=s.toLowerCase();
    	int n2=0;
    	int dem=0;
    	while(s.indexOf("<",n2)!=-1)
    	{
    		int n=s.indexOf("<");
    		int m=s.indexOf(">",n);	
    		
    		int m2=s.indexOf(" ",n);	
    		String t="";
    		if(m>m2)
    		{
        		if(n!=-1&&m!=-1)
            		t=s.substring(m2,m+1);
            		s=s.replace(t,"");
            		n2=m+1-t.length();
    		}
    		else
    		{
    			n2=m+1;	
    		}

    		
    		
    	}
    	s=s.replaceAll("\n","");
		s=s.replaceAll("\r","");
		s=s.replaceAll(" ","");
		s=convertToUTF8(s);
		s=s.replaceAll("\"","");
		s=s.replaceAll("/","");
		s=s.replaceAll("=","");

    	return s;
    }
    public String removeBorder3(String s)
    {
    	s=s.toLowerCase();
    	int n2=0;
    	int dem=0;
    	
    	while(s.indexOf("<!--",n2)!=-1)
    	{
    		int n=s.indexOf("<!--");
    		int m=s.indexOf("-->",n);	
    		String t="";
    		if(n!=-1&&m!=-1)
    		t=s.substring(n,m+1);
    		s=s.replace(t,"");
    		n2=m-t.length();
    	}
    	
    	n2=0;
    	
    	while(s.indexOf("<",n2)!=-1)
    	{
    		int n=s.indexOf("<",n2);
    		int m=s.indexOf(">",n);	
    		
    		int m2=s.indexOf(" ",n);	
    		String t="";
    		if(m>m2)
    		{
        		if(m2!=-1&&m!=-1)
            		t=s.substring(m2,m);
            		s=s.replace(t,"");
    		}

    		n2=m-t.length();
    		
    	}
    	s=s.replaceAll("\n","");
		s=s.replaceAll("\r","");
		s=s.replaceAll(" ","");
		s=convertToUTF8(s);
		s=s.replaceAll("\"","");
		s=s.replaceAll("/","");
		s=s.replaceAll("=","");

    	return s;
    }
    public int countCharFromString(String s)
    {
    	int n=0;
    	return n;
    }
    
    
    public String getElementString(Element e)
    {
    	String st="";
    	Elements le=e.children();
    	if(le.size()==0)
    	{
    		String w=e.ownText();
    		st=st+e.tagName()+w;
    		return st;
    	}
    	else
    	{
    		st=st+e.tagName();
	    	for(Element te:le)
	    	{
	    		String as=te.ownText();
	    		st=st+getElementString(te);
	    	}
	    	return st;
    	}	

    }
    
    public String getElementHtml(Element e)
    {
    	String t="";
    	t=getElementString(e);
    	
    	return t;
    }
    
   
    
    public Element getE( String html)
    {
    	String temp_html;
    	temp_html="<html>"+
    			"<head></head>"+
    			"<body>"+
    			html+
				"</body>"+
    			"</html>";
    	int htmllen=html.length();
    	int n2=html.indexOf("<");
    	int m=html.indexOf(" ",n2);
    	int m2=html.indexOf(">",n2);
    	String st="";
    	if(m>m2)
    	{
    		st=html.substring(n2+1,m2);
    	}
    	else
    	{
    		st=html.substring(n2+1,m);
    	}
    	
    	Document tDoc=Jsoup.parse(temp_html);
		Element htmlele=tDoc.children().get(0).children().get(1).child(0);
		String thtml=getElementHtml(htmlele);
		thtml=convertToUTF8(thtml);
		Elements le=document.getElementsByTag(st);	
		Element te=null;
		for(Element e:le)
		{
			if(e.children().size()==htmlele.children().size())
			{
				String st2=getElementHtml(e);
				st2=convertToUTF8(st2);
				if(st2.equals(thtml))
				{
					te=e;
				}
			}
		}
		
		if(te!=null)
				return te;
		st=htmlele.tagName();
		le=document.getElementsByTag(st);	
	
		for(Element e:le)
		{
			if(e.children().size()==htmlele.children().size())
			{
				String st2=getElementHtml(e);
				st2=convertToUTF8(st2);
				if(st2.equals(thtml))
				{
					te=e;
				}
			}
		}
		
		if(te!=null)		return te;
		thtml=htmlele.text();
		thtml=convertString(thtml);
		thtml=convertToUTF8(thtml);
		for(Element e:le)
		{
			if(e.children().size()==htmlele.children().size())
			{
				String st2=e.text();
				st2=convertString(st2);
				st2=convertToUTF8(st2);
				if(st2.equals(thtml))
				{
					te=e;
				}
			}
		}
		
		return te;
    }
    
    public String convertString(String s)
    {
    	s=s.replaceAll("\n", "");
    	s=s.replaceAll("\r", "");
    	s=s.replaceAll(" ","");
    	return s;
    }
    public Element getE2( String html)
    {
    	String temp_html=html;
    	int htmllen=html.length();
    	int n2=html.indexOf("<");
    	int m=html.indexOf(" ",n2);
    	int m2=html.indexOf(">",n2);
    	String st="";
    	if(m>m2)
    	{
    		st=html.substring(n2+1,m2);
    	}
    	else
    	{
    		st=html.substring(n2+1,m);
    	}
    	
    	
		html=removeBorder3(html);
		Elements le=document.getElementsByTag(st);	
		Element te=null;
		for(Element e:le)
		{

			String st2=e.outerHtml();
			st2=removeBorder3(st2);
			if(st2.equals(html))
			{
					te=e;
			}
			
		}
		
		
		return te;
    }
    
  
}



	
